<template>
  <el-dialog
    model-value="menuDialogVisible"
    title="分配权限"
    width="30%"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" label-width="100px">
      <el-tree
        ref="treeRef"
        node-key="id"
        :data="treeData"
        :props="defaultProps"
        show-checkbox
        :default-expand-all="true"
        :check-strictly="true"
      />
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, defineProps, ref, watch } from "vue";
import requestUtil, { getServerUrl } from "@/util/request";
import { ElMessage } from "element-plus";

const defaultProps = {
  children: "children",
  label: "name",
};

const props = defineProps({
  id: {
    type: Number,
    default: "",
    required: true,
  },
  menuDialogVisible: {
    type: Boolean,
    default: false,
    required: true,
  },
});

const treeRef = ref(null);

const treeData = ref([]);

const form = ref({
  id: "",
});

const formRef = ref(null);

const initFormData = async (id) => {
  const res = await requestUtil.get("menu/treeList");
  treeData.value = res.data.treeMenu;
  form.value.id = id;

  const res2 = await requestUtil.get("role/menus/" + id);
  //设置setCheckedKeys 被选中的节点 配合node-key 实现被默认选中
  treeRef.value.setCheckedKeys(res2.data.menuIdList);
};

watch(
  () => props.menuDialogVisible,
  () => {
    let id = props.id;
    console.log("id=" + id);
    if (id != "") {
      initFormData(id);
    }
  }
);

const emits = defineEmits(["update:modelValue", "initDate"]);

// 子组件关闭弹窗
const handleClose = () => {
  emits("update:modelValue", false);
};

const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      //获取前端用户点击的菜单列表的数组
      var menuIds = treeRef.value.getCheckedKeys();
      let res = await requestUtil.post(
        "role/grantMenu/" + form.value.id,
        menuIds
      );
      if (res.code == 20000) {
        ElMessage.success("执行成功！");
        emits("initDate");
        handleClose();
      } else {
        ElMessage.error(data.message);
      }
    } else {
      console.log("fail");
    }
  });
};
</script>

<style scoped>
</style>
